package com.itheima.reggie.controller;

import com.alibaba.excel.EasyExcel;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.Orders2;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {
    @Autowired(required = false)
    private OrderService orderService;

    @Autowired(required = false)
    private OrderMapper orderMapper;

    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders, HttpSession session){
        Long userId = (Long) session.getAttribute("user");
        orders.setUserId(userId);
        orderService.submit(orders);
        return R.success("下单成功");
    }

    @GetMapping("/userPage")
    public R<Page<OrdersDto>> userPage(Integer page, Integer pageSize, HttpSession session){
        Long userId = (Long) session.getAttribute("user");
        Page<OrdersDto> ordersPage =orderService.getUserPage(page,pageSize,userId);
        return R.success(ordersPage);
    }

    @GetMapping("/page")
    public R<Page<Orders>> page(Integer page,Integer pageSize,String number,String beginTime,String endTime){

        Page<Orders> pageResult = orderService.getOrdersPage(page,pageSize,number,beginTime,endTime);
        return R.success(pageResult);
    }

    /**
     * 文件下载（失败了会返回一个有部分数据的Excel）
     * <p>
     * 1. 创建excel对应的实体对象
     * <p>
     * 2. 设置返回的 参数
     * <p>
     * 3. 直接写，这里注意，finish的时候会自动关闭OutputStream,当然你外面再关闭流问题不大
     */
    @GetMapping("download")
    public void download(HttpServletResponse response) throws IOException {
        List<Orders> ordersList = orderMapper.findAll();
        log.info("ordersList");
        List<Orders2> orders2List = ordersList.stream().map(orders -> {
            Orders2 orders2 = new Orders2();
            orders2.setNumber(orders.getNumber());
            orders2.setStatus(orders.getStatus());
            orders2.setUserName(orders.getUserName());
            orders2.setPhone(orders.getPhone());
            orders2.setAddress(orders.getAddress());
            orders2.setTime(orders.getOrderTime().toString());
            orders2.setAmount(orders.getAmount());
            return orders2;
        }).collect(Collectors.toList());

        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Orders.class).sheet("模板").doWrite(orders2List);
    }
}
